#include "UILogger.h"
#include "UILog4CXXLogger.h"
#include "CommonUtil.h"
#include "UIOSAL.h"

#include <ctime>
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

UILogger* UILogger::m_pInstance = NULL;

void UILogger::create(UILoggerType type, std::string configFilePath)
{
	if (m_pInstance)
		return;
	
	switch (type) 
	{
	case LOGGER_LOG4CXX:
		m_pInstance = new UILog4CXXLogger();
	}

	m_pInstance->setLogPath();
	m_pInstance->initLogger(configFilePath);
}

void UILogger::release()
{
	if (m_pInstance)
		delete m_pInstance;
	m_pInstance = NULL;
}

UILogger* UILogger::getInstance()
{
	if (!m_pInstance) {
		create(DEFAULT_LOGGER, DEFAULT_LOGGER_CONFIG);
	}
	return m_pInstance;
}

UILogger::UILogger(void)
{
}

UILogger::~UILogger(void)
{
}

void UILogger::setLogPath(void)
{
	time_t t = time(NULL);
	tm* pTime = localtime(&t);

	char timetag[1024];
	sprintf(timetag, "%4d-%02d-%02d_%02d@%02d", 
		pTime->tm_year + 1900,
		pTime->tm_mon + 1,
		pTime->tm_mday,
		pTime->tm_hour,
		pTime->tm_min);

	if (mkdir("logs", 0777) != 0) {
		if (errno != EEXIST) {
			std::cout << "Failed to create log root dir: ./logs (errno=" << errno << ")" << std::endl;
			strcpy(m_logPath, "");
			strcpy(m_speechLogPath, "");
			strcpy(m_ttsLogPath, "");
			strcpy(m_logFilePrefix, "RTC-UI-System-Log-");
			strcat(m_logFilePrefix, timetag);
			return;
		}
	}

	strcpy(m_logPath, "logs/");
	strcat(m_logPath, timetag);
	std::cout << "Creating log dir: " << m_logPath << std::endl;
	if (mkdir(m_logPath, 0777) != 0) {
		if (errno != EEXIST) {
			std::cout << "Failed to create log dir: " << m_logPath << "(" << errno << ")" << std::endl;
			strcpy(m_logPath, "");
			strcpy(m_speechLogPath, "");
			strcpy(m_ttsLogPath, "");
			strcpy(m_logFilePrefix, "RTC-UI-System-Log-");
			strcat(m_logFilePrefix, timetag);
			return;
		}
	}

	strcpy(m_logFilePrefix, m_logPath);
	strcat(m_logFilePrefix, "/RTC-UI-System-Log-");
	strcat(m_logFilePrefix, timetag);

	strcpy(m_speechLogPath, m_logPath);
	strcat(m_speechLogPath, "/speechLog/");
	std::cout << "Creating speech log dir: " << m_speechLogPath << std::endl;
	if (mkdir(m_speechLogPath, 0777) != 0) {
		if (errno != EEXIST) {
			std::cout << "Failed to create speech log dir: " << m_speechLogPath << "(" << errno << ")" << std::endl;
			strcpy(m_speechLogPath, "");
			return;
		}
	}

	strcpy(m_ttsLogPath, m_logPath);
	strcat(m_ttsLogPath, "/ttsLog/");
	std::cout << "Creating tts log dir: " << m_ttsLogPath << std::endl;
	if (mkdir(m_ttsLogPath, 0777) != 0) {
		if (errno != EEXIST) {
			std::cout << "Failed to create tts log dir: " << m_ttsLogPath << "(" << errno << ")" << std::endl;
			strcpy(m_ttsLogPath, "");
			return;
		}
	}
}
